package com.bkitmobile.kesu.android.connectServer;

import java.io.InputStream;
import java.io.UTFDataFormatException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public abstract class ThreadWaitingReceive extends Thread implements ServiceCallback<String> {
	private List<BasicNameValuePair> nameValuePairs;

	public ThreadWaitingReceive(List<BasicNameValuePair> nameValuePairs) {
		super();
		this.nameValuePairs = nameValuePairs;
		if (staticClass.httpclient == null) {
			staticClass.httpclient = new DefaultHttpClient();
			staticClass.httppost = new HttpPost(staticClass.serviceURL);
		}
	}

	public void run() {
		try {
			String line = null, result = null;
			String charset = "UTF-8";
			InputStream is = null;
			staticClass.httppost.setEntity(new UrlEncodedFormEntity(
					nameValuePairs, charset));
			HttpResponse response = staticClass.httpclient
					.execute(staticClass.httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
			StringBuffer stringBuffer = new StringBuffer();
			char ch;
			int c;
			while ((c = is.read()) != -1) {
				ch = (char) c;
				stringBuffer.append(ch);
			}
			result = new String(stringBuffer);
			result = URLDecoder.decode(result, charset);
			onSuccess(result);
		} catch (Exception ex) {
			onFailure(ex);
		}
	}
}